<template>
  <template v-if="!readonly">
    <div class="popup-selector">
      <ZuiInput
        placeholder="请选择"
        round
        readonly
        @click="!disabled && (showPopup = true)"
        :modelValue="displayText"
        :disabled="disabled"
      >
        <template #suffix>
          <i class="icon-down iconfont-zui icon-zui-arrow-down"></i>
        </template>
      </ZuiInput>
      <ZuiPopup v-model:show="showPopup">
        <div class="popup-content">
          <header class="header">{{ title }}</header>
          <main class="main">
            <ZuiSelector :="$attrs" v-model="modelValue" />
          </main>
          <footer class="footer">
            <ZuiButton class="confirm-btn" type="primary" @click="onConfirmClick">确定</ZuiButton>
          </footer>
        </div>
      </ZuiPopup>
    </div>
  </template>
  <template v-else>
    <div class="popup-selector readonly">
      <span v-if="displayText">{{ displayText }}</span>
      <span v-else class="empty">未选择</span>
    </div>
  </template>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import ZuiInput from '../input/ZuiInput.vue'
import ZuiSelector from '../selector/ZuiSelector.vue'
import ZuiPopup from '../popup/ZuiPopup.vue'
import ZuiButton from '../button/ZuiButton.vue'

const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: { type: Array, default: () => [] },
  title: { type: String, default: '请选择' },
  disabled: Boolean,
  readonly: Boolean
})

const showPopup = ref(false)
const modelValue = ref()
const displayText = computed(() => {
  return props.modelValue
    .map((option) => {
      return option.addition ? `${option.label}(${option.addition})` : option.label
    })
    .join('/')
})

watch(
  () => props.modelValue,
  (val) => {
    modelValue.value = JSON.parse(JSON.stringify(val))
  },
  { immediate: true }
)
watch(showPopup, (val) => {
  if (val) {
    // 显示时使用外部数据初始化本地数据
    modelValue.value = JSON.parse(JSON.stringify(props.modelValue))
  }
})

function onConfirmClick() {
  showPopup.value = false
  emit('update:modelValue', modelValue.value)
}
</script>

<style lang="scss" scoped>
.popup-selector {
  &.readonly {
    line-height: var(--zui-size-line-height-regular);
    padding: 6px 12px;
    box-sizing: border-box;
    border-radius: var(--zui-size-border-radius-small);
    background-color: var(--zui-color-fill-light);
    .empty {
      color: var(--zui-color-text-secondary);
    }
  }
  .icon-down {
    line-height: 32px;
    padding: 0 12px;
    color: var(--zui-color-text-secondary);
  }
}
.popup-content {
  .header {
    font-size: var(--zui-size-text-large);
    line-height: var(--zui-size-line-height-large);
    padding: 12px 20px;
    text-align: center;
  }
  .main {
    padding: 12px 20px;
    max-height: 70vh;
    overflow: auto;
  }
  .footer {
    padding: 0 20px 24px 20px;
    .confirm-btn {
      width: 100%;
    }
  }
}
</style>
